package com.jiantong.web.controller.AB_Certificate;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiantong.user.model.BreedFactory;
import com.jiantong.user.model.ButcherFactory;
import com.jiantong.user.service.BreedFactoryReadService;
import com.jiantong.user.service.ButcherFactoryReadService;
import com.jiantong.work.model.BreedReport;
import com.jiantong.work.model.BreedReportSurveyRecord;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Response;
import io.terminus.common.utils.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 动物AB证,开证工具类
 * Created by mz03 on 2017/5/2.
 */
@RestController
@Slf4j
public class AnimalCertificateUtil {

    private static final String ZZLX = "3";                                                                                              //1:A证,3:B证
    private static final String JYLX = "1";                                                                                              //1:产地检疫  2- 挎县分销动物检疫  4-其它系统对接
    private static final String FLAG = "DONG_YANG";
    private static final String COMMAND = "71";
    private static final String SERVICE = "4";
    private static final String USER_ID = "28540";
    private static final String CREDENTIAL_URL = "http://114.215.249.190:8080/app/app?";
    @RpcConsumer
    private static BreedFactoryReadService  breedFactoryReadService;
    @RpcConsumer
    private static ButcherFactoryReadService butcherFactoryReadService;

    private static final ObjectMapper objectMapper = JsonMapper.nonEmptyMapper().getMapper();
    Boolean isSucceed = false;

    @GetMapping(value = "/test/12/1")
    public static Response<Object> isSucceed(BreedReport breedReport, BreedReportSurveyRecord breedReportSurveyRecord){

        BreedFactory breedFactory = breedFactoryReadService.findById(breedReport.getBreedFactoryId()).getResult();
        if (breedReport.getButcherFactoryId()!=null){
            ButcherFactory butcherFactory = butcherFactoryReadService.findButcherFactoryById(breedReport.getButcherFactoryId()).getResult();
        }

        String jyhgzmbh = "3389200008";                                                                               //检疫证明编号
        String hzName = breedReport.getOwner();                                                                         //货主名字
        String hzLxdh = breedReport.getOwnerMobile();                                                                   //货主联系电话
        String animalTypeId = CertificateUtil.kind(breedReport.getBreedType())+"";                                      //动物种类id 82:猪
        String sl = breedReport.getQuantity()+"";                                                                       //开证数量 quantity
        String ggdw = CertificateUtil.unitShift(breedReport.getUnit())+"";                                              //规格单位id
        String qydRegionId = breedFactory.getRegionId()+"";                                                             //起运地-地区id
        while (qydRegionId.length() < 12){
            qydRegionId = qydRegionId +"0";
        }
        String qydRegionName = breedFactory.getRegion();                                                                //起运地-地区名称
        String qydXxdz = breedFactory.getDetail();                                                                      //起运地-详细地址
        String qydCslx = CertificateUtil.BREED_FACTORY+"";                                                           //起运地-场所类型
        String mddRegionId = "0951";                                               //目的地-地区id  根据详细地址找到地区名 根据地区名确定地区ID 补齐12位
        while (mddRegionId.length() < 12){
            mddRegionId = mddRegionId +"0";
        }
        String mddRegionName = "0951区";                                            //目的地-地区名称  根据详细地址找到地区名
        String mddXxdz = breedReport.getReceiveAddress();                                                               //目的地-详细地址
        String mddCslx = CertificateUtil.BUTCHER_FACTORY+"";                                                         //目的地-场所类型
        String yt = CertificateUtil.use(breedReport.getPurposeType())+"";                                               //用途
        String xqbsxx = breedReportSurveyRecord.getQuarantineCertNumber();                                              //畜禽标识信息(B证必填)quarantine_cert_number
        String sbztRegionId = "0000";                                               //申报主体所在地区id 货主所在地区
        while (sbztRegionId.length() < 12){
            sbztRegionId = sbztRegionId +"0";
        }
        String qfsj = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss").format(new Date());                      //签发时间 当前时间
        String qfUserName = breedReportSurveyRecord.getSurveyUserName();                                                 //签发人名称  开证人  survey_user_name

        Map<String,String> map = new HashMap<>();
        map.put("command",COMMAND);
        map.put("service",SERVICE);
        map.put("userid",USER_ID);
        map.put("jyhgzmbh",jyhgzmbh);
        map.put("zzlx",ZZLX);
        map.put("jylx",JYLX);
        map.put("flag",FLAG);
        map.put("hzName",hzName);
        map.put("hzLxdh",hzLxdh);
        map.put("animalTypeId",animalTypeId);
        map.put("sl",sl);
        map.put("ggdw",ggdw);
        map.put("qydRegionId",qydRegionId);
        map.put("qydRegionName",qydRegionName);
        map.put("qydXxdz",qydXxdz);
        map.put("qydCslx",qydCslx);
        map.put("yt",yt);
        map.put("xqbsxx",xqbsxx);
        map.put("qfsj",qfsj);
        map.put("sbztRegionId",sbztRegionId);
        map.put("mddRegionId",mddRegionId);
        map.put("mddRegionName",mddRegionName);
        map.put("mddXxdz",mddXxdz);
        map.put("mddCslx",mddCslx);
        map.put("qfUserName",qfUserName);
        String credentialUrl = CREDENTIAL_URL;

        for (String key : map.keySet()) {
            credentialUrl += key+"="+map.get(key)+"&";
        }
//        根据查出来的参数, 组成一个get请求的URL
//        credential_url = "http://114.215.249.190:8080/app/app?command=71&service=4&userid=28540&jyhgzmbh=3389200008&zzlx=3&jylx=1&flag=dongYang&hzName=1&hzLxdh=1&animalTypeId=82&sl=1&ggdw=103&qydRegionId=057900000000&qydRegionName=1&qydXxdz=1&qydCslx=1&mddRegionId=33018300004&mddRegionName=1&mddXxdz=1&mddCslx=1&yt=1&xqbsxx=1&cyr=1&cyrLxdh=18800010001&yxq=2&ysfs=1&ysgjPh=123456&ysgjXdqk=1&dwwsjdsLxdh=1&qfsj=2017-04-12%2012:09:33&sbztRegionId=057900000000&qfUserName=123";
        Boolean isSucceed = false;
        String credentialUrl2 = "http://114.215.249.190:8080/app/app?mddRegionName=0951区&flag=DONG_YANG&ggdw=104&mddCslx=2&sbztRegionId=000000000000&userid=28540&qfUserName=戚小伟&hzLxdh=112&qydRegionId=765000000000&qfsj=2017-05-09%2011:37:25&sl=12&yt=20&qydCslx=1&xqbsxx=4694949566&jylx=1&hzName=测试1&jyhgzmbh=3389200008&command=71&animalTypeId=83&zzlx=3&mddXxdz=上海市静安区文化大道123号&service=4&qydRegionName=滨江1&qydXxdz=风情大道123号&mddRegionId=095100000000";
        try {
            URL url = new URL(credentialUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
           int code = connection.getResponseCode();
            if (code == 404) {
                log.error("认证无效，找不到此次认证的会话信息！");
                return Response.fail("404错误");
            }
            if (code == 500) {
                log.error("认证服务器发生内部错误");
                return Response.fail("500错误");
            }
            if (code != 200) {
                log.error("发生其它错误，认证服务器返回"+ code);
                return Response.fail(code + "错误");
            }
            InputStream is = connection.getInputStream();
            byte[] response = new  byte[is.available()];
            is.read(response);
            is.close();
            if (response == null || response.length == 0) {
                log.error("认证无效，找不到此次认证的会话信息！");
                return Response.fail("认证无效！");
            }
            String userId = new String(response, "UTF-8");

            //打印返回结构
            Map<String , String> resultMap = objectMapper.readValue(userId, new TypeReference<Map<String , String>>(){});
            System.out.println(resultMap.get("msg"));
            System.out.println(resultMap.get("id"));
            System.out.println(resultMap.get("code"));

            //判断是否成功, 成功改变isSucceed为true
            if (resultMap.get("code").equals("1")) {
                isSucceed = true;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果成功  写入打印表djt_issuance_table
        //
        //记录到打印表
        return Response.ok(null); //返回一个打印表实体类对象
    }

}
